package com.yc.pre.schedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yc.pre.entity.bean.ChangeObligors;
import com.yc.pre.entity.bean.LabModelAuctionExtract;
import com.yc.pre.entity.bean.Obligors;
import com.yc.pre.entity.bean.PreDataPool;
import com.yc.pre.service.LabModelAuctionService;
import com.yc.pre.service.PreDataPoolService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName DataSyncSchedule
 * @Description 数据同步定时任务（每周同步一次，每次同步时间为每周末晚上24点）
 * @Date 2021/02/21 16:51:59
 * @Created by ccc-j
 * @email ccc-ju@outlook.com
 */
@Component
@EnableScheduling // 开启定时任务
@EnableAsync // 开启多线程
@Slf4j
public class DataSyncSchedule {

    @Autowired
    private LabModelAuctionService labModelAuctionService;

    @Autowired
    private PreDataPoolService preDataPoolService;

    @Async
    @Scheduled(cron = "0 0 0 */1 * ?")  //每天24点自动执行
    //@Scheduled(fixedDelay = 600000)    //每隔600秒钟执行一次
    @Transactional
    public void projectStatusUpdateFixedSchedule() throws InterruptedException{
        log.info("定时任务开始执行-----------------------------");
        // 1.先查询试标库数据
        List<PreDataPool> dataPools = preDataPoolService.findAll();
        List<Integer> ids = dataPools.stream().map(x -> x.getId()).collect(Collectors.toList());
        // 2.通过查询出来的id查询资产监控库
        List<LabModelAuctionExtract> originalDatas = labModelAuctionService.findExtractByIds(ids);
        // 3.将数据进行转换
        List<PreDataPool> changeDatas = new ArrayList<>();
        for (LabModelAuctionExtract originalData : originalDatas) {
            // 需要处理一下债务人列表信息
            String obligors = originalData.getObligors();
            // 原始Obligors
            List<Obligors> list = JSON.parseArray(obligors, Obligors.class);
            // 转换存储起来的Obligors
            List<ChangeObligors> changes = new ArrayList<>();
            // 需要存储的json字符串
            String storeObligors = "";
            if(StringUtils.isNotBlank(obligors) && !obligors.equals("[]")){
                for (Obligors ob : list) {
                    changes.add(ChangeObligors.builder()
                            .birthday(ob.getBirthday())
                            .gender(ob.getGender())
                            .label_type(ob.getLabel_type())
                            .name(ob.getName())
                            .notes(ob.getNotes())
                            .number(ob.getNumber())
                            .build());
                }
                storeObligors = JSONObject.toJSON(changes).toString();
            }
            // build_area为0以下时候，转存则为空
            BigDecimal buildingArea = originalData.getBuildingArea();
            if(ObjectUtils.isEmpty(buildingArea) || buildingArea.doubleValue() <= 0.00){
                buildingArea = new BigDecimal("0.00");
            }
            // 填充对象
            PreDataPool preDataPool = new PreDataPool();
            preDataPool.setId(originalData.getId());
            preDataPool.setTitle(originalData.getTitle());
            preDataPool.setAuctionStatus(originalData.getStatus());
            preDataPool.setCollateralStatus(originalData.getCollateral());
            preDataPool.setHouseLandType(originalData.getHouseType());
            preDataPool.setBuildingArea(buildingArea);
            preDataPool.setDocumentFindStatus(originalData.getWsFindStatus());
            preDataPool.setDocumentCaseNumber(originalData.getAh());
            preDataPool.setDocumentLinkAddress(originalData.getWsUrl());
            preDataPool.setDocumentInAttach(originalData.getWsInAttach());
            preDataPool.setObligors(originalData.getObligors());

            changeDatas.add(preDataPool);
        }
        // 4.更新数据池的数据
        Integer number = preDataPoolService.updatePoolData(changeDatas);
        log.info("定时任务执行完毕-----------------------------");
        log.info("成功更新 " + number + " 条数据");
    }

    /*public static void main(String[] args) {
        String obligors = "[{\"birthday\":\"\",\"gender\":\"0\",\"label_type\":\"5\",\"name\":\"邢小娟\",\"notes\":\"\",\"number\":\"\",\"system\":1,\"type\":\"5\"},{\"birthday\":\"19720226\",\"gender\":\"1\",\"label_type\":\"1\",\"name\":\"汤强\",\"notes\":\"\",\"number\":\"\",\"type\":\"1\"}]";
        //String obligors = "[]";
        // 需要处理一下债务人列表信息
        // 原始Obligors
        List<Obligors> list = JSON.parseArray(obligors, Obligors.class);
        // 转换存储起来的Obligors
        List<ChangeObligors> changes = new ArrayList<>();
        // 需要存储的json字符串
        String storeObligors = "";
        if(StringUtils.isNotBlank(obligors) && !obligors.equals("[]")){
            for (Obligors ob : list) {
                changes.add(ChangeObligors.builder()
                        .birthday(ob.getBirthday())
                        .gender(ob.getGender())
                        .label_type(ob.getLabel_type())
                        .name(ob.getName())
                        .notes(ob.getNotes())
                        .number(ob.getNumber())
                        .build());
            }
            storeObligors = JSONObject.toJSON(changes).toString();
        }
        System.out.println(storeObligors);
    }*/

}
